<?php
/**
 * @author Inhere
 * @version v1.0
 * Use : session操作管理服务
 * Date : 2015-1-10
 * SessionServiceProvider.php
 */
namespace ulue\base\providers;

use ulue\core\ioc\Container,
    ulue\parts\session\Session;
use ulue\parts\db\Db;
use ulue\parts\session\handler\InterfaceSessionHandler;

class SessionServiceProvider extends AbstractConfigurableServiceProvider
{
    /**
     * 注册 Session 服务， SessionServiceProvider
     * @param  Container $container 传入容器
     * @throws \DInvalidArgumentException
     * @return mixed|void
     */
    public function register(Container $container)
    {
        $self = $this;

        $closure = function(Container $container) use ($self)
        {
            $options        = $self->options;
            $driver         = isset($options['handler']) ? $options['handler'] : 'Nature';
            $driverObject   = $self->getDriver($driver, $options);

            return new Session($driverObject, null, null, $options);
        };

        $container->share('session', $closure)->alias('app.session')->alias('system.session');

    }

    /**
     * 获取具体的session驱动实例
     * @param $driver
     * @param $options
     * @return mixed
     * @throws \DRuntimeException
     */
    protected function getDriver($driver, $options)
    {
        if (strpos($driver,'\\') && class_exists($driver)) {
            $object = new $driver($options);

            if ($object instanceof InterfaceSessionHandler)
            {
                return $object;
            }
        }

        !$driver && $driver = 'Nature';

        $class = sprintf('ulue\parts\session\handler\%sSessionHandler', ucfirst($driver));

        if(!class_exists($class))
        {
            throw new \DRuntimeException(sprintf('没有找到需要的session处理驱动类: %s ！',$driver));
        }

        if($driver=='db' || $driver=='database')
        {
            $db = Db::getInstance();

            return new $class($db, $options);
        }

        return new $class($options);
    }
}